package de.hft_stuttgart.dsa.ctt.writer;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import de.hft_stuttgart.dsa.ctt.model.Course;
import de.hft_stuttgart.dsa.ctt.model.CourseAssignmentMatrix;
import de.hft_stuttgart.dsa.ctt.model.ProblemInstance;
import de.hft_stuttgart.dsa.ctt.model.Room;

public class SolutionWriter {

	private static final String SOLUTION_FOLDER = "Solutions";

	private String pathToFile;

	public SolutionWriter() {
		File file = new File("");
		pathToFile = file.getAbsolutePath();
	}

	/**
	 * @param problemInstance
	 * @param courseAssignmentMatrix
	 */
	public void writeSolutionToFile(ProblemInstance problemInstance, CourseAssignmentMatrix courseAssignmentMatrix) {
		Date date = new Date();
		SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMdd_HHmmssS");
		String fileName = pathToFile + File.separator + SOLUTION_FOLDER + File.separator + problemInstance.getName() + "_" + dataFormat.format(date) + ".ctt";
		System.out.println(fileName);
		File file = new File(fileName);
		try {
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
			Object[][] matrix = courseAssignmentMatrix.getPeriodRoomMatrix();
			List<Room> rooms = problemInstance.getRoomsOrderedByCapacity();
			int periodsPerDay = problemInstance.getPeriodsPerDay();
			for (int i = 0; i < matrix.length; ++i) {
				int periodOfDay = i % periodsPerDay;
				int day = i / periodsPerDay;
				List<Course> courses = new ArrayList<Course>(rooms.size());
				for (int j = 0; j < matrix[i].length; ++j) {
					Course course = (Course) matrix[i][j];
					String courseId = course.getCourseId();
					if (null != courseId) {
						courses.add(course);
					}
				}
				Collections.sort(courses , new Comparator<Course>() {

					@Override
					public int compare(Course course1, Course course2) {
						return course1.compareStudentNumbers(course2);
					}
				});
				for (int listIndex = 0; listIndex <courses.size(); ++listIndex) {
					Course course = courses.get(listIndex);
					// output format: <CourseID> <RoomID> <Day> <Day_Period>
					StringBuffer sb = new StringBuffer(course.getCourseId());
					sb.append(" ");
					sb.append(rooms.get(listIndex).getRoomId()); 
					sb.append(" ");
					sb.append(day);
					sb.append(" ");
					sb.append(periodOfDay);
					bufferedWriter.append(sb.toString());
					bufferedWriter.newLine();
				}				
			}
			bufferedWriter.flush();
			bufferedWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
